/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.display {
	import com.googlecode.milib.base.MLBroadcastClass;
	import com.googlecode.milib.display.service.MLMC;

	import flash.display.MovieClip;

	/**
	 * @author Marek Brun
	 */
	public class MCDuplicator extends MLBroadcastClass {				private var duplicatedMC:MovieClip;		private var dupliationsCount:int=0;		private var prefix:String;
		private var mlmcParent:MLMC;
		
		public function MCDuplicator(duplicatedMC:MovieClip) {			this.duplicatedMC=duplicatedMC;
			if(!duplicatedMC.parent){
				throw new Error('duplicatedMC must have parent');
			}
			mlmcParent=MLMC.forInstance(MovieClip(duplicatedMC.parent));
//			if(isNaN(Number(duplicatedMC.name.substr(-1)))){
//				duplicatedMC.name=duplicatedMC.name+'0';
//			}
			if(isNaN(parseInt(duplicatedMC.name.substr(-1)))){
				prefix=duplicatedMC.name;
			}else{
				prefix=duplicatedMC.name.substr(0, -1);
				for(var i:uint=0;true;i++){
					if(mlmcParent.gotInstanceByName(prefix+i)){
						dupliationsCount++;
						break;
					}
				}
			}					}				public function gotMC(index:Number):Boolean {			return mlmcParent.gotInstanceByName(prefix+index);		}				public function getNewMC():MovieClip {			dupliationsCount++;			if(mlmcParent.gotInstanceByName(prefix+dupliationsCount)){				return MovieClip(mlmcParent.getMC(prefix+dupliationsCount));			}else{				return createNewMC(dupliationsCount);			}		}				public function getMCByIndex(index:Number):MovieClip {			if(mlmcParent.gotInstanceByName(prefix+index)){				return mlmcParent.getMC(prefix+index);			}else{				return createNewMC(index);			}		}				private function createNewMC(mcNum:int):MovieClip {
			if(duplicatedMC.constructor===MovieClip){
				throw new Error('duplicatedMC.constructor===MovieClip - plase set library class for duplicated clip with instance name "'+duplicatedMC+'"');
			}			var mcClass:Class=Class(duplicatedMC.constructor);			var newMC:MovieClip=MovieClip(new mcClass());			newMC.name=prefix+mcNum;			mlmcParent.mc.addChild(newMC);
			dupliationsCount=Math.max(dupliationsCount, mcNum);			return newMC;		}
		
		public function getAllMCS():Array {
			var allMCS:Array=[];
			var i:uint;
			for(i=0;i<dupliationsCount;i++){
				if(mlmcParent.gotInstanceByName(prefix+i)){
					allMCS.push(mlmcParent.getMC(prefix+i));
				}
				
			}
			return allMCS;
		}			}}